﻿using Enuo.Dotnet.Api.Models;
using Enuo.Dotnet.Core.Model;
using Enuo.Dotnet.Service;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Enuo.Dotnet.Api.Service
{
  public class AuthenticateService : IAuthenticateService
  {
    public readonly JwtConfig tokenModel;
    private readonly AccountService accountService;
    public AuthenticateService(IOptions<JwtConfig> jwtModel, AccountService accountService)
    {
      tokenModel = jwtModel.Value;
      this.accountService = accountService;
    }

    public bool IsAuthenticated(LoginVo user)
    {
      return accountService.ValidateLogin(user.userName, user.password);
    }

    public LoginResult Authorization(LoginVo user)
    {
      var claims = new[] {
                new Claim(ClaimTypes.Name,user.userName)
            };
      //密钥
      var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenModel.Secret));
      //凭证
      var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
      //生成Token
      var jwtToken = new JwtSecurityToken(tokenModel.Issuer, tokenModel.Audience, claims,
          expires: DateTime.Now.AddMinutes(tokenModel.AccessExpiration),
          signingCredentials: credentials);
      var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
      var info = accountService.FindByWhere(s => s.name == user.userName);
      var result = new LoginResult()
      {
        token = token,
        type = "Bearer",
        profile = info.Result
      };
      return result;
    }
  }
}
